<?PHP
require_once("base.wpfb.php");
require_once ('src/facebook.php');

class ImportFacebookAlbum extends WpEnvironemt{

private $parentPage = null;
private $AlbumInsertPage = null;
private $globalVars = null;

public function __construct($parentPage, $AlbumInsertPage)
{
	$this->globalVars = new WPFB($parentPage);
	$this->parentPage = $parentPage;
	$this->AlbumInsertPage = $AlbumInsertPage;
}

protected function initAllVariables() {}

public function processAlbum()
{
	if( isset($_GET['facebook_download_req']) )
	{
		$token = "220636254729676|jdk3XW2f-FbDts2cS-V1VX6y8J4";
		$data = file_get_contents($_GET['url']);
		echo $data;
		exit();
	}
	if( isset($_GET['post']) )
		$this->processAlbumasNewWordpressPost();
	else	
		$this->processAlbumasNewWordpressPost_UI();
}
private function processAlbumasNewWordpressPost()
{
	try{
		global $current_user;
		get_currentuserinfo();

		if( isset($_POST['title']) || isset($_POST['content']) || isset($_POST['data']))
		{
			//throw new Exception('Some parameter(s) is missing');
			if( isset($_POST['tags_input']) )
				$tags_input = explode(';', $_POST['tags_input']);
			
			$imageDiv = $_POST['data'];
			
			$content = $_POST['content'];
			$content .= "<div id='parent'>$imageDiv</div><script type='text/javascript' src='http://buetian-dot-com-theme-wordpress.googlecode.com/svn/Trunk/buetian4.0/lib/bjqs-execute.js'></script>";
//			print_r($content);die;
			
			$my_post = array(
				'post_title' => $_POST['title'],
				'post_content' => $content,
				'post_status' => 'pending',
				'post_author' => $current_user->ID,
				'tags_input' => $tags_input,
				'filter' => true
			);
			
			$post_id = wp_insert_post( $my_post, true );
			if( is_wp_error($post_id) )
			{ 
				throw new Exception($post_id->get_error_message());
			}
			echo "Successfully queued and having pending status: ". get_bloginfo('siteurl'). '/?p='. $post_id;
		}
		else
			throw new Exception('Somehow post title or post content were not sent to server. Please try again.');
	}catch(Exception $e)
	{
		$this->printException($e);
	}
	exit(); //This was an ajax request.
}

private function processAlbumasNewWordpressPost_UI()
{
?>
<h1> Import FacebookAlbum as a Wordpress post </h1>
Insert Album id:
<input type="text" value="" size="50" maxlength="1000" id="my_Album" noBanglaText='noBanglaText' onclick='select();' />
<button class="click" ID="importAlbum">Import</button>
<br/><small>Not all public albums of facebook users can be imported, however albums from facebook pages can be imported always</small>
<br/><small><code><a href='https://developers.facebook.com/tools/explorer/220636254729676/?method=GET&path=youtube%2Falbums%3Ffields%3Dname%2Cdescription%2Clink%26limit%3D10'>Help</a> or Example: https://www.facebook.com/#!/media/set/?set=a.{THIS-IS-THE-ALBUM-ID}.1073741848.194570894065437&type=1</code></small>

<div  style='width:600px;'>
<br/><br/><br/><span style='color:red'></span><br/>
<table id="data_table" border="1">
<thead>
<tr>
<th>Serial</th>
<th>Title of the post</th>
<th>Import link</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

<script type='text/javascript' src='//cdn.datatables.net/1.10.0/js/jquery.dataTables.js'></script>
<style type="text/css">@import url("//cdn.datatables.net/1.10.0/css/jquery.dataTables.css");</style>
<style type="text/css">td { max-width: 100px; }</style>
<script type="text/javascript">

(function($){
$('#data_table').dataTable({'aaSorting': [[ 0, 'desc' ]]} );

$("#importAlbum").click(function(){
	var access_token = "<?PHP echo $this->globalVars->facebook->getAccessToken(); ?>";
	var url=$("#my_Album").val();
	
	if(isNaN(parseFloat(url)) || !isFinite(url))
	{
		//It's not numeric
		alert("Album id must be numeric");
		return;
	}
	
	var json = $.getJSON("https://graph.facebook.com/v2.2/"+url+"?callback=?&access_token="+access_token+"&id="+url+"&fields=link,name,from,count,photos{link,picture,name,images}&limit=20",
	function(data)
	{
		// importedData = a global variable; not good
		if( data.error != null)
		{
			alert("Error: " + data.error.message);
			return;
		}
		importedData = data;
		
		importedData.title = data.name;
		
		importedData.content = "";
		importedData.content += "<strong>পরিচয়: </strong> "+ data.from.name;
		importedData.content += "<br/><strong>ছবি সংখ্যা: </strong>"+ data.count; 
		
		var prevText = '<div id="slider-code" class="viewport"><ul class="bjqs" style="position:relative; list-style:none;padding:0;margin:0;overflow:hidden; display:none;">';
		var afterText = "</ul></div>";
		var images = "";
		
		for(var i =0; i< data.photos.data.length; ++i)
		{
			var image = data.photos.data[i];
			var title = typeof image.name == "undefined" ? "" : image.name;
			var src = image.images[1].source;
			
			images+="<li style='position:absolute; display:none;'><a target='_blank' href='"+src+"'><img title='"+title+"' style='' src='"+ src+"'/></a></li>";
		}
		
		importedData.data = prevText+images+afterText;
		importedData.link = data.link;
		importedData.content += "<br/><div style='display:none'><strong>মূল লিংক: </strong> <a href='"+importedData.link+"' target='_blank'>"+importedData.link+"</a></div>";
		
		$('#data_table').dataTable().fnAddData([0, data.name, '<button onclick="insertPost()" style="font-style:bold" >Submit</button>']);
	});
	
	insertPost= function()
	{
		var data={
			title: importedData.title,
			content: importedData.content,
			link: importedData.link,
			data: importedData.data,
			tags_input: 'facebook-album'
		};
		
		$.post("<?PHP echo get_bloginfo('wpurl') . "/wp-admin/admin-ajax.php?action={$this->AlbumInsertPage}&post=post2"; ?>", data,
		function(response)
		{
			//console.log(response);
			alert(response);
			$('#data_table').dataTable().fnDeleteRow(0);
		});
	}
});

//end of function
})(jQuery);
</script>

<br/><br/><br/><br/>

<?php 
}
private function array2json($arr) {
    if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
    $parts = array();
    $is_list = false;

    //Find out if the given array is a numerical array
    $keys = array_keys($arr);
    $max_length = count($arr)-1;
    if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
        $is_list = true;
        for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
            if($i != $keys[$i]) { //A key fails at position check.
                $is_list = false; //It is an associative array.
                break;
            }
        }
    }

    foreach($arr as $key=>$value) {
        if(is_array($value)) { //Custom handling for arrays
            if($is_list) $parts[] = array2json($value); /* :RECURSION: */
            else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
        } else {
            $str = '';
            if(!$is_list) $str = '"' . $key . '":';

            //Custom handling for multiple data types
            if(is_numeric($value)) $str .= $value; //Numbers
            elseif($value === false) $str .= 'false'; //The booleans
            elseif($value === true) $str .= 'true';
            else $str .= '"' . addslashes($value) . '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Object?)

            $parts[] = $str;
        }
    }
    $json = implode(',',$parts);
    
    if($is_list) return '[' . $json . ']';//Return numerical JSON
    return '{' . $json . '}';//Return associative JSON
} 
} // class ends here
?>